//
//  KABillListCell.swift
//  kano
//
//  Created by Frank on 2024/9/12.
//

import UIKit
import RxCocoa
import RxSwift

class KABillListCell: UITableViewCell {
    
    var repayHandler:(()->())?
    
    var model: KALoanListModel = KALoanListModel() {
        didSet {
            //重用回复
            dueDateTitle.text = "Due Date"
            dueDateTitle.textColor = .color615F67
            dueDateLabel.isHidden = false
            var_repayBtn.isHidden = false
            var_tipLabel.isHidden = false
            var_bottomTip.isHidden = false
            var_bottomTipImg.isHidden = false
            var_bottomTipLabel.isHidden = false
            amountTitle.isHidden = false
            amountLabel.isHidden = false
            
            if model.tadpoleLoanIndicator {
                var_bottomTip.isHidden = false
                var_bottomTipImg.isHidden = false
                var_bottomTipLabel.isHidden = false
                var_bgView.image = UIImage(named: "billList_bg_big")
            }
            else {
                var_bottomTip.isHidden = true
                var_bottomTipImg.isHidden = true
                var_bottomTipLabel.isHidden = true
                var_bgView.image = UIImage(named: "billList_bg_white")
            }
            
            //打款中
            if model.operationalStatus == 0 || model.operationalStatus == 9 {
                dueDateTitle.text = "Payment in Process (The latest arrival time is within 24 hours)"
                dueDateTitle.textColor = .themeColor
                dueDateLabel.isHidden = true
                var_repayBtn.isHidden = true
                var_tipLabel.isHidden = true
            }
            //借款失败
            else if model.operationalStatus == 8 || model.operationalStatus == 99 {
                var_bottomTip.isHidden = false
                var_bottomTipImg.isHidden = false
                var_bottomTipLabel.isHidden = false
                var_tipLabel.isHidden = true
                dueDateLabel.isHidden = true
                dueDateTitle.isHidden = true
                var_repayBtn.isHidden = true
                if model.operationalStatus == 8 {
                    var_bottomTipLabel.text = "The loan failed due to network or payment channel problems. Please try to initiate the loan again."
                } else if model.operationalStatus == 99 {
                    var_bottomTipLabel.text = "Because the bank card you bind has not been activated, you are unable to borrow. Currently, our company is unable to authenticate your true identity."
                }
                var_bgView.image = UIImage(named: "billList_bg_white")
            }
            
            // 1、4 待还款
            //           else if model.operationalStatus == 1 || model.operationalStatus == 4 {
            //大额
            if model.credentialData?.count ?? 0 > 0 && !model.tadpoleLoanIndicator {
                var subLoanModel: KARecordSubLoans = KARecordSubLoans()
                for subLoan in model.credentialData! {
                    //repaymentStatus==3 已还款
                    if subLoan.emailProvider != 3 {
                        subLoanModel = subLoan
                        break
                    }
                }
                amountTitle.isHidden = false
                amountLabel.isHidden = false
                balanceTitle.text = "Repayment balance"
                balanceLabel.text = "₦" + "\(model.registrationConfirmation.separatorString())"
                monthPayLabel.text = "₦" + "\(subLoanModel.advanceRemaining.separatorString())"
                amountLabel.text = "\(subLoanModel.repaymentTiming)/\(model.credentialData!.count)Phase"
                dueDateLabel.text = Date.ka_stringWith(timestamp: subLoanModel.dueDateTime, format: "dd/MM/yyyy")
                
                updateUI(overDueDays: subLoanModel.overdueDuration)
            }
            //蝌蚪、小额
            else {
                if model.tadpoleLoanIndicator {
                    amountTitle.isHidden = false
                    amountLabel.isHidden = false
                    //蝌蚪贷贷款金额
                    balanceTitle.text = "Repayment balance"
                    balanceLabel.text = "₦" + "\(model.registrationConfirmation.separatorString())"
                    //蝌蚪贷待还金额
                    monthPayLabel.text = "₦" + "\(model.remainingLoanBalance.separatorString())"
                    amountLabel.text = "1/2Phase"
                    dueDateLabel.text = Date.ka_stringWith(timestamp: model.dueDateTime, format: "dd/MM/yyyy")
                } else {
                    amountTitle.isHidden = true
                    amountLabel.isHidden = true
                    //待还金额
                    balanceTitle.text = "Repayment amount"
                    balanceLabel.text = ""
                    monthPayLabel.text = "₦" + "\(model.registrationConfirmation.separatorString())"
                    dueDateLabel.text = Date.ka_stringWith(timestamp: model.dueDateTime, format: "dd/MM/yyyy")
                }
                updateUI(overDueDays: model.overdueDuration)
            }
            //            }
            
        }
    }
    
    func updateUI(overDueDays: Int) {
        if overDueDays >= -3 &&  overDueDays < -1 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due after \(abs(overDueDays)) day"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            dueDateLabel.textColor = .colorFF8921
        }
        else if overDueDays == -1 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due Tomorrow"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            dueDateLabel.textColor = .colorFF8921
        }
        else if overDueDays == 0 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due Today"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            dueDateLabel.textColor = .colorFF8921
        }
        else if overDueDays > 0 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "overdue \(abs(overDueDays)) day"
            var_tipLabel.textColor = .colorFF3644
            var_tipLabel.backgroundColor = .colorFFE8E8
            dueDateLabel.textColor = .colorFF3644
        } else {
            var_tipLabel.isHidden = true
            var_tipLabel.textColor = .themeColor
            dueDateLabel.textColor = .themeColor
        }
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        self.contentView.backgroundColor = .white
    }
    
    lazy var headerBg: UIView = {
        let headerBg = UIView()
        headerBg.isHidden = true
        headerBg.backgroundColor = .colorF6F6F6
        return headerBg
    }()
    lazy var var_bgView: UIImageView = {
        let var_bgView = UIImageView(image: UIImage(named: "billList_bg_white"))
        var_bgView.isUserInteractionEnabled = true
        return var_bgView
    }()
    
    public var balanceTitle: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(12), weight: .medium)
        label.textColor = .color8A8891
        label.text = "Repayment balance"
        return label
    }()
    
    public var balanceLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(12), weight: .medium)
        label.textColor = .color323135
        label.text = ""
        return label
    }()
    
    public var monthPayLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(22), weight: .bold)
        label.textColor = .color323135
        label.text = ""
        return label
    }()
    
    public var amountTitle: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(12), weight: .medium)
        label.textColor = .color8A8891
        label.text = "Repayment amount"
        return label
    }()
    
    public var amountLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(12), weight: .medium)
        label.textColor = .color323135
        label.text = ""
        return label
    }()
    
    lazy var var_repayBtn: UIButton = {
        let var_repayBtn = UIButton()
        var_repayBtn.backgroundColor = .white
        var_repayBtn.addTarget(self, action: #selector(ka_repayBtnClick), for: .touchUpInside)
        var_repayBtn.setTitle("Repay now", for: .normal)
        var_repayBtn.setTitleColor(.themeColor, for: .normal)
        var_repayBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(12), weight: .bold)
        var_repayBtn.layer.borderWidth = 1
        var_repayBtn.layer.borderColor = UIColor.themeColor.cgColor
        var_repayBtn.layer.cornerRadius = 8
        var_repayBtn.layer.masksToBounds = true
        return var_repayBtn
    }()
    
    @objc func ka_repayBtnClick() {
        if (repayHandler != nil) {
            repayHandler!()
        }
    }
    
    public var dueDateTitle: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(11), weight: .medium)
        label.textColor = .color615F67
        label.text = "Due Date"
        return label
    }()
    
    public var dueDateLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(11), weight: .medium)
        label.textColor = .colorFF8921
        label.text = ""
        return label
    }()
    
    lazy var var_tipLabel: KAEdgeLabel = {
        let label = KAEdgeLabel(edgeInsets: UIEdgeInsets(top: 0, left: 6, bottom: 0, right: 6))
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(9), weight: .medium)
        label.textColor = .colorFF8921
        label.text = "Due Today"
        label.backgroundColor = .colorFFE9D5
        label.layer.cornerRadius = 10
        label.layer.masksToBounds = true
        return label
    }()
    
    lazy var var_bottomTip: UIView = {
        let var_bottomTip = UIView()
        return var_bottomTip
    }()
    lazy var var_bottomTipImg: UIImageView = {
        let var_bottomTipImg = UIImageView(image: UIImage(named: "tadpoleLoanTip"))
        var_bottomTipImg.isUserInteractionEnabled = true
        return var_bottomTipImg
    }()
    lazy var var_bottomTipLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(11), weight: .regular)
        label.textColor = .black
        label.text = "On time repayment, we will waive the full amount of the second installment for you"
        label.numberOfLines = 2
        return label
    }()
    
    
    static func ka_cell(for tableView: UITableView) -> KABillListCell {
        let var_identifityId = NSStringFromClass(self)
        var var_cell = tableView.dequeueReusableCell(withIdentifier: var_identifityId)
        if var_cell == nil {
            var_cell = KABillListCell.init(style: .default, reuseIdentifier: var_identifityId)
        }
        return var_cell as! KABillListCell
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        ka_setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KABillListCell {
    func ka_setUI() {
        backgroundColor = .white
        contentView.addSubview(headerBg)
        contentView.addSubview(var_bgView)
        var_bgView.addSubview(balanceTitle)
        var_bgView.addSubview(balanceLabel)
        var_bgView.addSubview(monthPayLabel)
        var_bgView.addSubview(amountTitle)
        var_bgView.addSubview(amountLabel)
        var_bgView.addSubview(var_repayBtn)
        var_bgView.addSubview(dueDateTitle)
        var_bgView.addSubview(dueDateLabel)
        var_bgView.addSubview(var_tipLabel)
        var_bgView.addSubview(var_bottomTip)
        var_bottomTip.addSubview(var_bottomTipImg)
        var_bottomTip.addSubview(var_bottomTipLabel)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        headerBg.snp.makeConstraints { make in
            make.left.equalTo(contentView).offset(kscale(12));
            make.right.equalTo(contentView).offset(kscale(-12));
            make.top.equalTo(0);
            make.height.equalTo(kscale(20));
        }
        var_bgView.snp.makeConstraints { make in
            make.left.equalTo(contentView).offset(kscale(12));
            make.right.equalTo(contentView).offset(kscale(-12));
            make.bottom.equalTo(contentView).offset(-0.5);
            make.top.equalTo(contentView).offset(0.5);
        }
        balanceTitle.snp.makeConstraints { make in
            make.top.equalTo(kscale(26))
            make.left.equalTo(kscale(16))
        }
        balanceLabel.snp.makeConstraints { make in
            make.centerY.equalTo(balanceTitle)
            make.left.equalTo(balanceTitle.snp.right).offset(kscale(8))
        }
        
        monthPayLabel.snp.makeConstraints { make in
            make.left.equalTo(kscale(16))
            make.top.equalTo(balanceTitle.snp.bottom).offset(kscale(2))
        }
        
        amountTitle.snp.makeConstraints { make in
            make.left.equalTo(kscale(16))
            make.top.equalTo(monthPayLabel.snp.bottom).offset(kscale(4))
        }
        amountLabel.snp.makeConstraints { make in
            make.centerY.equalTo(amountTitle)
            make.left.equalTo(amountTitle.snp.right).offset(kscale(8))
        }
        var_repayBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(83, 30))
            make.right.equalTo(var_bgView).offset(kscale(-12));
            make.top.equalTo(amountTitle.snp.bottom).offset(kscale(22))
        }
        dueDateTitle.snp.makeConstraints { make in
            make.left.equalTo(kscale(16))
            make.top.equalTo(amountTitle.snp.bottom).offset(kscale(22))
        }
        dueDateLabel.snp.makeConstraints { make in
            make.left.equalTo(dueDateTitle.snp.right).offset(kscale(8))
            make.top.equalTo(dueDateTitle)
        }
        
        var_tipLabel.snp.makeConstraints { make in
            make.centerY.equalTo(dueDateTitle)
            make.left.equalTo(dueDateLabel.snp.right).offset(kscale(8))
            make.height.equalTo(kscale(20))
        }
        
        var_bottomTip.snp.makeConstraints { make in
            make.right.equalTo(kscale(-16))
            make.left.equalTo(kscale(16))
            make.height.equalTo(kscale(40))
            make.bottom.equalTo(kscale(-26))
        }
        var_bottomTip.addHorizontalGradientLayer(startColor: UIColor.ka_hexString("#FFECDB").cgColor, endColor: UIColor.ka_hexString("#FFFFFF").cgColor)
        var_bottomTip.layer.cornerRadius = 6
        var_bottomTip.layer.masksToBounds = true
        
        var_bottomTipImg.snp.makeConstraints { make in
            make.left.equalTo(kscale(8))
            make.height.width.equalTo(kscale(24))
            make.centerY.equalTo(var_bottomTip)
        }
        var_bottomTipLabel.snp.makeConstraints { make in
            make.left.equalTo(var_bottomTipImg.snp.right).offset(kscale(8))
            make.top.equalTo(kscale(4))
            make.bottom.right.equalTo(kscale(-4))
        }
        
    }
    
    
}
